<?php
/**
 * 管理画面親コントローラー
 *
 * @package  app
 * @extends  Controller
 */
require_once __DIR__ . '/../../thirdpirty/ApnsPHP/Autoload.php';

class Controller_Manage extends Controller_Apibase {
	/**
	 * コンストラクタ
	 *
	 * @access  public
	 * @return  Response
	 */
	public function before() {
		set_time_limit(180); // 時間制限無し
		
		$this -> auth = false;
		$this -> log = false;
		parent::before();

		$manage = Config::get('manage');

		// Basic認証
		// if (!isset($_SERVER["PHP_AUTH_USER"])) {
			// header("WWW-Authenticate: Basic realm=\"Please Enter Your Password\"");
			// header("HTTP/1.0 401 Unauthorized");
			// exit ;
		// } else {
			// $auth = $_SERVER["PHP_AUTH_USER"] . "/" . $_SERVER["PHP_AUTH_PW"];
			// if (array_search($auth, $manage['basicauth']) === false) {
				// throw new HttpNotFoundException;
			// }
		// }
	}

	/**
	 * テストプッシュ通知
	 *
	 * @access  public
	 * @return  Response
	 */
	public function apns_test($text) {
		$member = Config::get('test_push_member_id');
		foreach($member as $m) {
			$query = DB::select('devicetoken');
			$query->from('member_info');
			$query->where('member_id', $m);
			$result = $query->execute()->as_array();
			if( count($result) == 0) {
				continue;
			}
			
			$this->apns_push( array(0 => array('token' => $result[0]['devicetoken'], 'text' => $text)) );
		}
	}
	
 	/**
	 * プッシュ通知
	 * 一回あたり256バイト、一回の接続で5000バイト、という送信制限があるので注意
	 *
	 * @access  public
	 * @return  Response
	 */
	public function apns_push($messages = array()) {
		$ret = true;
		
		if( $_SERVER['FUEL_ENV'] == Fuel::PRODUCTION ) {
			// 本番機
			$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, __DIR__ . '/../../data/apns/apns_commesodo_production.pem');
		} else {
			// 開発機
			$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, __DIR__ . '/../../data/apns/apns_commesodo_development.pem');
		}
		$push -> connect();
               // $count = count($messages);
                //$i=0;
		try{
			foreach ($messages as $message) {
                                $i++;
				$data = new ApnsPHP_Message($message['token']);
				$data -> setBadge(1);
				$data -> setSound();
				$data -> setText($message['text']);
				$data -> setExpiry(30);
				$push -> add($data);
                               
			}
			$push -> send();
			$aErrorQueue = $push -> getErrors();
			if (!empty($aErrorQueue)) {
				// デバッグ表示
				$ret = $aErrorQueue;
			}
		} catch (ApnsPHP_Message_Exception $e){
                        if($i<$count)
                            
			$ret = $e->getMessage();
 		}
		$push -> disconnect();
				
		return $ret;
	}

 	/**
	 * リワード加工
	 *
	 * @access  public
	 * @return  Response
	 */
	public function reward_api2view($company = '') {
		$query = DB::select('ad_company','ad_id','post_date','data');
		$query -> from('reward_api');
		if( $company ) {
			$query -> where('ad_company', $company);
		}
		$query -> where('del', 0);
		$query -> order_by('ad_id', 'DESC');
		$result = $query -> execute() -> as_array();
		
		$list = array();
		foreach ($result as $r) {
			$value = json_decode($r['data'], true);
			$l = array(
				'ad_company' => $r['ad_company'],
				'ad_id' => $r['ad_id'],
				'post_date' => $r['post_date'],
				'score' => 100
			);
			
			switch( $r['ad_company'] ) {
				//-----------------------------
				// AppDriver
				//-----------------------------
				case 'appdrv' :
					// Androidは除外
					if( $value['platform'] == 3) {
						continue;
					}

					// 成果地点
					$value['advertisement'] = isset($value['advertisement'][0]) ? $value['advertisement'] : array(0 => $value['advertisement']);
					if( count($value['advertisement']) == 1 ) {
						$v = $value['advertisement'][0];
						$point = $v['point'];
						$payment = $v['payment'];
						$subtitle = $v['name'];
						$adv = sprintf('%sで%dポイントGET', $v['name'], $point ) . chr(13);
						
					} else {
						$adv = '';
						$point = 0;
						$payment = 0;
						$subtitle = '';
						$i = 0;
						foreach( $value['advertisement'] as $v) {
							$point = $point < $v['point'] ? $v['point'] : $point;
							$payment = $payment < $v['payment'] ? $v['payment'] : $payment;
							$i ++;
							if( $v['period'] == 0) {
								$adv .= sprintf('%d. %sで%dポイントGET', $i, $v['name'], $point ) . chr(13);
							} else {
								$adv .= sprintf('%d. %s後、%d日程度で%dポイントGET', $i, $v['name'], $v['period'], $point) . chr(13);
							}
							if( $subtitle == '') {
								$subtitle = $v['name'];
							}
						}
						
						// 成果地点が複数あるものは優先度落とす
						$l['score'] = 10;
					}
					
					$l['title'] = $value['name'];
					$l['subtitle'] = $subtitle;
					$l['advertisement'] = $adv;
					$l['description'] = !empty($value['detail']) ? $value['detail'] : '';
					$l['notice'] = !is_array($value['remark']) ? $value['remark'] : ''; // 無いときarrayになる
					$l['link'] = $value['location'];
					$l['icon'] = $value['icon'];
					$l['point'] = $point;
					$l['payment'] = $payment;
					
					// カテゴリ
					$l['category'] = '';
					if( $value['platform'] == 1 ) {
						$l['category'] .= 'web,';
					}
					if( $value['platform'] == 2 ) {
						$l['category'] .= 'apl,';
						$l['score'] += 10;
					}
					if( $value['price'] == 0 ) {
						$l['category'] .= 'free,';
						$l['score'] += 5;
					}
					
					// CPI案件
					if( $l['point'] > 0 && strpos( $l['subtitle'], 'インストール') !== false ) {
						// CPI
						$l['score'] = 5000;
					}
					
					$list[] = $l;
					break;
				//-----------------------------
				// SMAAD
				//-----------------------------
				case 'smaad' :
					$t = array('dl' => 'ダウンロード', 'request' => '会員登録・申し込み', 'ec' => '商品購入');
					// iOS対応判定
					//if(strpos($value['Os'], 'iphone') === false) {
					//	continue;
					//}
					
					$l['title'] = $value['Title'];
					$l['subtitle'] = $value['Condition'];
					$l['advertisement'] = $value['Condition'];
					$l['description'] = $value['Description'];
					$l['notice'] = '';
					$l['link'] = $value['Link'] . '&u=';
					$l['icon'] = $value['Icon'];
					$l['point'] = ceil($value['Net'] * Config::get('reward_smaad_rate'));
					$l['payment'] = $value['Net'];
					
					// カテゴリ
					$l['category'] = '';
					if( $value['Type'] == 'request' ) {
						$l['category'] .= 'web,';
					}
					if( $value['Type'] == 'dl' ) {
						$l['category'] .= 'apl,';
						$l['score'] += 10;
					}
					if( $value['Price'] == 0 ) {
						$l['category'] .= 'free,';
						$l['score'] += 5;
					}
					
					// CPI案件
					if( $l['point'] > 0 && $value['Price'] == 0 && $value['Type'] == 'dl' ) {
						// 無料、ダウンロード
						$l['score'] = 5000;
					}
					
					$list[] = $l;
					break;
				//-----------------------------
				// CAリワード
				//-----------------------------
				case 'ca' :
					// 成果地点
					$ps = array(
						1 => 'インストール',
						2 => '無料会員登録',
						3 => '有料会員登録',
						4 => 'キャンペーン',
						5 => '商品購入',
						6 => 'サンプル請求',
						7 => 'アンケート・モニター登録',
						8 => '資料請求',
						9 => '見積・査定',
						10 => 'クレジットカード申込・発券',
						11 => 'キャッシング申込・成約',
						12 => '口座開設',
						13 => '予約・来店',
						14 => 'その他',
					);
					$value['p'] = isset($value['p'][0]) ? $value['p'] : array( 0 => $value['p']); 
					if( count($value['p']) == 1 ) {
						$v = $value['p'][0];
						$payment = $v['amount'];
						$p = ceil($v['amount'] * Config::get('reward_ca_rate'));
						$g = isset($ps[ $v['requisite_id'] ]) ? $ps[ $v['requisite_id'] ] : 'その他';
						$adv = sprintf('%sで%dポイントGET', $g, $p) . chr(13);
						$subtitle = $g;
						
					} else {
						$payment = 0;
						$adv = '';
						$subtitle = '';
						$i = 0;
						foreach( $value['p'] as $v) {
							$payment = $payment < $v['amount'] ? $v['amount'] : $payment;
							
							$i ++;
							$p = ceil($v['amount'] * Config::get('reward_ca_rate'));
							$g = isset($ps[ $v['requisite_id'] ]) ? $ps[ $v['requisite_id'] ] : 'その他';
							$adv .= sprintf('%d. %sで%dポイントGET', $i, $g, $p) . chr(13);
						
							if( $subtitle == '' ) {
								$subtitle = $g;
							}
						}
						
						// 成果地点が複数あるものは優先度落とす
						$l['score'] = 10;
					}
					
					$l['title'] = $value['banner_text_1'];
					$l['subtitle'] = $subtitle;
					$l['advertisement'] = $adv;
					$l['description'] = str_replace('<br>', chr(13), $value['content_exp']);
					$l['notice'] =  str_replace('<br>', chr(13), $value['count_type_for_user']);
					$l['link'] = str_replace('&user_id=_dummy_', '', $value['ad_tag_of_point_back']) . '&user_id=';
					$l['icon'] = $value['banner_img_1'];
					$l['point'] = ceil($payment * Config::get('reward_ca_rate'));
					$l['payment'] = $payment;
					
					// カテゴリ
					$l['category'] = '';
					if( $value['is_app'] == '0' ) {
						$l['category'] .= 'web,';
					}
					if( $value['is_app'] == '1' ) {
						$l['category'] .= 'apl,';
						$l['score'] += 10;
					}
					if( $value['charge_type'] == '2' ) {
						$l['category'] .= 'free,';
						$l['score'] += 5;
					}
					
					// CPI案件
					if( $l['point'] > 0 && $value['charge_type'] == '2' && $value['is_install_action'] == '1' ) {
						$l['score'] = 5000;
					}
					
					$list[] = $l;
					break;
				//-----------------------------
				// Affilead
				//-----------------------------
				case 'affile' :
					// iOS対応判定
					if(strpos($value['carrier'], 'io') === false) {
						continue;
					}

					// 定額報酬
					if($value['reward_type'] != '1') {
						continue;
					}
					
					// 反映が即時
					if($value['reflection'] != '1') {
						continue;
					}
					
					// 評価
					if($value['recommend'] <= 1) {
						continue;	
					}
					
					// 文言の変更
					if($value['allow_change'] == '1') {
						continue;	
					}
					
					$intr = explode('▼', $value['introduction']);
					
					$l['title'] = $value['name'];
					$l['subtitle'] = $value['reward_memo'];
					$l['advertisement'] = $value['reward_memo'];
					$l['description'] = trim($intr[0]);
					$l['notice'] = '';
					$l['point'] = ceil($value['reward'] * Config::get('reward_affilead_rate'));
					$l['payment'] = $value['reward'];

					// 左右幅のもっとも小さい画像をアイコンにする
					$wh = 0;
					foreach ($value['tag'] as $t) {
						preg_match('/href="(.*)"><img/is', $t, $retArr);
						if (!isset($retArr[1])) {
							continue;
						}
						$l['link'] = $retArr[1] . '&option=';

						preg_match('/<img src="(.*)" alt=/is', $t, $retArr);
						if (!isset($retArr[1])) {
							continue;
						}
						$img = $retArr[1];
						try {
							$ckey = $this -> ckey('ad', 'affilead', 'image', $img);
							$s = Cache::get($ckey);
							Log::debug('Cache Hit');
						} catch (\CacheNotFoundException $e) {
							list($width, $height) = getimagesize($img);
							$s = $height / $width;
							Cache::set($ckey, $s);
						}
						if ($s > $wh) {
							$l['icon'] = $retArr[1];
							$wh = $s;
						}
					}
					if (!isset($l['icon'])) {
						continue;
					}
					
					// カテゴリ
					$l['category'] = '';
					
					$list[] = $l;
					break;
			}

		}

		return $list;
	}
}
